<template>
    <div class="room-manage-wrap">
        <n-page-header class="page-header" title="客房管理工作台" subtitle="让旅客有个温暖的家" @back="handleBack">
            <n-grid :cols="6">
                <n-gi>
                    <n-statistic label="总房间" :value="roomStatistics.totalRoom + ' 间'" />
                </n-gi>
                <n-gi>
                    <n-statistic label="空闲" :value="roomStatistics.vacancy + ' 间'" />
                </n-gi>
                <n-gi>
                    <n-statistic label="已预定" :value="roomStatistics.ordered + ' 间'" />
                </n-gi>
                <n-gi>
                    <n-statistic label="正在使用" :value="roomStatistics.inUsed + ' 间'" />
                </n-gi>
                <n-gi>
                    <n-statistic label="正在维修清理" :value="roomStatistics.inRepaired + ' 间'" />
                </n-gi>
                <n-gi>
                    <n-statistic label="停用" :value="roomStatistics.banned + ' 间'" />
                </n-gi>
            </n-grid>
            <template #avatar>
                <n-avatar size="large">{{ userStore.userNickname }}</n-avatar>
            </template>
            <template #extra>
                <n-space>
                    <n-button>催更</n-button>
                    <n-dropdown :options="options" placement="bottom-start">
                        <n-button :bordered="false" style="padding: 0 4px">
                            ···
                        </n-button>
                    </n-dropdown>
                </n-space>
            </template>
            <template #footer>
                <n-divider title-placement="left">
                    房间预览
                </n-divider>
            </template>
        </n-page-header>
        <div class="room-board">
            <n-card embedded bordered>
                <n-space :vertical="true">
                    <n-space>
                        <n-button @click="filterAddress">Filter Address (London)</n-button>
                        <n-button @click="clearFilters">Clear Filters</n-button>
                    </n-space>
                    <n-data-table ref="table" striped single-column :single-line="false" :bordered="false"
                        :columns="roomInfoTableColumns" :data="roomInfoData" />
                </n-space>
            </n-card>
        </div>
        <n-drawer v-model:show="activeOrderCheckIn" :width="502" :placement="placement">
            <n-drawer-content title="入住旅客信息">
                <n-list hoverable clickable>
                    <n-list-item v-for="guestInfo in checkInUserInfo?.userInfoList" :key="guestInfo.userNickname">
                        <n-thing :title="guestInfo.userNickname" content-style="margin-top: 10px;">
                            <template #description>
                                <n-space size="small" style="margin-top: 4px">
                                    年龄:<n-tag v-if="parseInt(guestInfo.userAge) >= 18" :bordered="false" type="info" size="small">
                                        {{guestInfo.userAge}}
                                    </n-tag>
                                    <n-tag v-else :bordered="false" type="warning" size="small">
                                        {{guestInfo.userAge}}
                                    </n-tag>
                                    性别:<n-tag v-if="guestInfo.userGender=='男'" :bordered="false" type="info" size="small">
                                        {{guestInfo.userGender}}
                                    </n-tag>
                                    <n-tag v-else :bordered="false" type="error" size="small">
                                        {{guestInfo.userGender}}
                                    </n-tag>
                                    联系方式:<n-tag :bordered="false" type="info" size="small">
                                        {{guestInfo.telephone}}
                                    </n-tag>
                                    身份证号:<n-tag :bordered="false" type="info" size="small">
                                        {{guestInfo.residentId}}
                                    </n-tag>
                                </n-space>
                            </template>
                        </n-thing>
                    </n-list-item>
                </n-list>
                <template #footer>
                    <n-space size="small" style="margin-top: 4px">
                        <n-date-picker v-model:value="range" type="datetimerange" clearable />
                        <n-button @click=" showModal = true">添加入住用户</n-button>
                        <n-button @click="confirmCheckIn">确定入住</n-button>
                    </n-space>
                </template>
            </n-drawer-content>
        </n-drawer>
          <n-modal
            v-model:show="showModal"
            class="custom-card"
            preset="card"
            style="width: 600px"
            title="入住旅客信息填写"
            size="huge"
            :bordered="false"
            :segmented="{
                content: 'soft',
                footer: 'soft',
            }"
        >
            <template #header-extra>
            
            </template>
            <n-form
                ref="formRef"
                inline
                :label-width="80"
                :model="formValue"
                :rules="checkInUserRules"
                size="medium"
            >
                <n-grid :cols="20" :x-gap="24">
                    <n-form-item-gi :span="10" label="姓名" path="userNickname">
                    <n-input v-model:value="formValue.userNickname" placeholder="输入姓名" />
                    </n-form-item-gi>
                    <n-form-item-gi :span="10" label="年龄" path="userAge">
                    <n-input v-model:value="formValue.userAge" placeholder="输入年龄" />
                    </n-form-item-gi>
                    <n-form-item-gi :span="10" label="电话号码" path="telephone">
                    <n-input v-model:value="formValue.telephone" placeholder="电话号码" />
                    </n-form-item-gi>
                    <n-form-item-gi :span="10" label="身份证号" path="residentId">
                    <n-input v-model:value="formValue.residentId" placeholder="身份证号" />
                    </n-form-item-gi>
                    <n-form-item-gi :span="10" label="性别" path="userGender">
                    <n-input v-model:value="formValue.userGender" placeholder="性别" />
                    </n-form-item-gi>
                    <n-form-item-gi :span="10">
                    <n-button attr-type="button" @click="handleUserAddClick">
                        添加
                    </n-button>
                    </n-form-item-gi>
                </n-grid>
            </n-form>
            <template #footer>
                请填写入住旅客基本信息
            </template>
        </n-modal>
        <n-drawer v-model:show="activeUserInfo" :width="502" :placement="placement">
            <n-drawer-content title="住房用户信息">
                <n-list hoverable clickable>
                <n-list-item v-for="guestInfo in roomGuestUserList" :key="guestInfo.userId">
                    <n-thing :title="guestInfo.userNickname" content-style="margin-top: 10px;">
                        <template #description>
                            <n-space size="small" style="margin-top: 4px">
                                年龄:<n-tag v-if="guestInfo.userAge >= 18" :bordered="false" type="info" size="small">
                                    {{guestInfo.userAge}}
                                </n-tag>
                                <n-tag v-else :bordered="false" type="warning" size="small">
                                    {{guestInfo.userAge}}
                                </n-tag>
                                性别:<n-tag v-if="guestInfo.userGender=='男'" :bordered="false" type="info" size="small">
                                    {{guestInfo.userGender}}
                                </n-tag>
                                <n-tag v-else :bordered="false" type="error" size="small">
                                    {{guestInfo.userGender}}
                                </n-tag>
                                联系方式:<n-tag :bordered="false" type="info" size="small">
                                    {{guestInfo.telephone}}
                                </n-tag>
                                身份证号:<n-tag :bordered="false" type="info" size="small">
                                    {{guestInfo.residentId}}
                                </n-tag>
                            </n-space>
                        </template>
                        <span v-if="guestInfo.checkInTime == null">
                            入住时间: 尚未入住<br/>
                        </span>
                        <span v-else>
                            入住时间: {{moment(guestInfo.checkInTime).format("YYYY-MM-DD HH:mm:ss")}}<br/>
                        </span>
                        退房时间: {{ moment(guestInfo.checkOutTime).format("YYYY-MM-DD HH:mm:ss") }}
                    </n-thing>
                </n-list-item>
                </n-list>
            </n-drawer-content>
        </n-drawer>
    </div>
</template>

<script setup lang="ts">
import { useMessage, NTag, NButton, useNotification, NDropdown, DrawerPlacement } from 'naive-ui'
import useUserStore from "@/store/modules/user"
import { roomRequest } from '@/api';
import { onMounted, reactive, ref, h } from 'vue';
import type {
    DataTableColumns,
    DataTableBaseColumn
} from 'naive-ui';
import moment from 'moment'
moment.locale('zh-cn')

const message = useMessage();
const userStore = useUserStore();
const notification = useNotification();

interface roomStatisticsVO {
    totalRoom: number
    vacancy: number
    ordered: number
    inUsed: number
    inRepaired: number
    banned: number
}

const roomStatistics = reactive<roomStatisticsVO>({
    totalRoom: 1,
    vacancy: 0,
    ordered: 0,
    inUsed: 0,
    inRepaired: 0,
    banned: 0,
})

function handleBack() {
    message.info('[onBack]')
}

function getStatistics() {
    roomRequest.getRoomStatistics().then(resp => {
        if (resp.data.code == 200) {
            roomStatistics.totalRoom = resp.data.data.roomNumber
            roomStatistics.vacancy = resp.data.data.roomVacancyNumber
            roomStatistics.ordered = resp.data.data.roomOrderedNumber
            roomStatistics.inUsed = resp.data.data.roomUsedNumber
            roomStatistics.inRepaired = resp.data.data.roomRepairedNumber
            roomStatistics.banned = resp.data.data.roomBannedNumber
        }
    });
}

const options = [
    {
        label: '催更',
        key: '1'
    },
    {
        label: '催更',
        key: '2'
    },
    {
        label: '催更',
        key: '3'
    }
]
type RoomInfoRowData = {
    roomId: number,
    roomName: string,
    roomTypeName: string,
    bedTypeName: string,
    tagList: string[],
    roomStatus: string,
}


const tagColumn = reactive<DataTableBaseColumn<RoomInfoRowData>>({
    title: '标签',
    key: 'tagList',
    filterMultiple: true,
    filterOptionValue: null,
    sorter: 'default',
    filterOptions: [
        {
            label: '是否有网',
            value: '有网',
        },
        {
            label: '是否有早餐',
            value: '有早餐',
        }
    ],
    filter(value, row) {
        row.tagList.forEach(e => {
            if (value.toString().match(e)) {
                return true;
            }
        })
        return false;
    },
    render(row) {
        const tags = row.tagList.map((tagKey) => {
            if (tagKey.startsWith("无")) {
                return h(
                    NTag,
                    {
                        style: {
                            marginRight: '6px'
                        },
                        type: 'warning',
                        bordered: false
                    },
                    {
                        default: () => tagKey
                    }
                )
            } else if (tagKey.startsWith("有")) {
                return h(
                    NTag,
                    {
                        style: {
                            marginRight: '6px'
                        },
                        type: 'success',
                        bordered: false
                    },
                    {
                        default: () => tagKey
                    }
                )
            } else {
                return h(
                    NTag,
                    {
                        style: {
                            marginRight: '6px'
                        },
                        type: 'info',
                        bordered: false
                    },
                    {
                        default: () => tagKey
                    }
                )
            }
        })
        return tags
    }
})

const createColumns = (
    { handleSelect }: {
        handleSelect: (keys: string | number, rowData: RoomInfoRowData) => void
    }): DataTableColumns<RoomInfoRowData> => {
    return [
        {
            title: "Id",
            key: "roomId",
        },
        {
            title: '房间名',
            key: 'roomName'
        },
        {
            title: '房型',
            key: 'roomTypeName'
        },
        {
            title: '床型',
            key: 'bedTypeName'
        },
        tagColumn,
        {
            title: '房间状态',
            key: 'roomStatus'
        },
        {
            title: '操作',
            key: 'actions',
            render(row) {
                let renderOperationRoomOption: {
                    label: string;
                    key: string;
                }[] = [];
                if (row.roomStatus.includes("空闲")) {
                    renderOperationRoomOption = vacancyRoomOption;
                } else if (row.roomStatus.includes("已用")) {
                    renderOperationRoomOption = usedRoomOption;
                } else if (row.roomStatus.includes("已预定")) {
                    renderOperationRoomOption = orderedRoomOption;
                } else if (row.roomStatus.includes("打扫中")) {
                    renderOperationRoomOption = repairingRoomOption;
                } else if (row.roomStatus.includes("停用")) {
                    renderOperationRoomOption = canceledRoomOption;
                }
                return h(
                    NDropdown,
                    {
                        size: 'large',
                        placement: 'top-start',
                        trigger: 'click',
                        options: renderOperationRoomOption,
                        onSelect: (key: string | number) => {
                            handleSelect(key, row)
                        }
                    },
                    {
                        default: () => h(
                            NButton,
                            {},
                            {
                                default: () => "操作"
                            }
                        )
                    }
                )
            }
        },
    ]
}

let roomInfoData = reactive<RoomInfoRowData[]>([
    {
        bedTypeName: "大软床",
        roomId: 4,
        roomName: "204",
        roomStatus: "未用",
        roomTypeName: "豪华双床房",
        tagList: ["haha", "haha"]
    },
])

const getRoomDetailInfoData = () => {
    roomRequest.getRoomDetailInfoList().then(resp => {
        if (resp.data.code == 200) {
            roomInfoData.length = 0;
            roomInfoData.push(...resp.data.data)
            console.log(roomInfoData)
        } else {
            notification.error({
                content: "错误",
                meta: `${resp.data.message}`,
                keepAliveOnHover: true,
                duration: 2500,
            })
        }
    })
}

const getRoomGuestInfoList = (roomId:number) => {
    roomRequest.queryRoomGuestInfo(roomId).then(resp => {
        if (resp.data.code == 200) {
            roomGuestUserList.length = 0;
            roomGuestUserList.push(...resp.data.data);
        } else {
            notification.error({
                content: "错误",
                meta: `${resp.data.message}`,
                keepAliveOnHover: true,
                duration: 2500,
            })
        }
    })
}

const activeOrderCheckIn = ref(false);
const activeUserInfo = ref(false);
const placement = ref<DrawerPlacement>('right')
const showModal = ref(false)

const activateGuestOrderCheckInDrawer = (place: DrawerPlacement) => {
    activeOrderCheckIn.value = true
    placement.value = place
}
const activateUserInfoDrawer = (place: DrawerPlacement) => {
    activeUserInfo.value = true
    placement.value = place
}


const roomInfoTableColumns = createColumns({
    handleSelect(keys: string | number, rowData: RoomInfoRowData) {
        // message.info('send Message To ' + rowData + "选项keys为 " + keys)
        switch (keys) {
            //  usedRoomOption
            case '1':
                //  退房
                roomRequest.checkOut({
                    roomId: rowData.roomId
                }).then(resp => {
                    if (resp.data.code == 200) {
                        message.success("退房成功");
                        //// TODO wrap here
                        getRoomDetailInfoData();
                        getStatistics();
                    } else {
                        message.error(`${resp.data.message}`);
                    }
                })
                break;
            case '2':
                //  清洁服务
                roomRequest.updateRoomStatus({
                    roomId: rowData.roomId,
                    roomStatus: 3,
                }).then(resp => {
                    if (resp.data.code == 200) { 
                        message.success("修改成功")
                        // rowData.roomStatus = "打扫中"
                        //// TODO wrap here
                        getRoomDetailInfoData();
                        getStatistics();
                    } else {
                        message.error(`${resp.data.message}"`)
                    }
                })
                break;
            case '3':
                //  查询住户信息
                activateUserInfoDrawer(placement.value);
                getRoomGuestInfoList(rowData.roomId)
                break;
            //  vacancyRoomOption
            case '4':
                //  用户入住
                activateGuestOrderCheckInDrawer(placement.value);
                checkInUserInfo.value.userInfoList.length = 0
                checkInUserInfo.value.estimatedCheckInTime = 0
                checkInUserInfo.value.estimatedCheckOutTime = 0
                currentRoomId.value = rowData.roomId
                break;
            case '5':
                //  打扫
                roomRequest.updateRoomStatus({
                    roomId: rowData.roomId,
                    roomStatus: 3,
                }).then(resp => {
                    if (resp.data.code == 200) {
                        message.success("修改成功")
                        // rowData.roomStatus = "打扫中"
                        //// TODO wrap here
                        getRoomDetailInfoData();
                        getStatistics();
                    } else {
                        message.error(`${resp.data.message}"`)
                    }
                })
                break;
            case '6':
                //  暂停出售
                roomRequest.updateRoomStatus({
                    roomId: rowData.roomId,
                    roomStatus: 4,
                }).then(resp => {
                    if (resp.data.code == 200) {
                        message.success("修改成功")
                        // rowData.roomStatus = "停用"
                        //// TODO wrap here
                        getRoomDetailInfoData();
                        getStatistics();
                    } else {
                        message.error(`${resp.data.message}"`)
                    }
                })
                break;
            //  orderedRoomOption
            case '7':
                //  取消预订
                roomRequest.cancelOrder({
                    roomId: rowData.roomId
                }).then(resp => {
                    if (resp.data.code == 200) {
                        message.success("取消成功")
                        getRoomDetailInfoData();
                        getStatistics();
                    } else if (resp.data.code == 444) {
                        message.error(`${resp.data.message}"`)
                    }
                })
                break;
            case '8':
                activateUserInfoDrawer(placement.value);
                getRoomGuestInfoList(rowData.roomId)
                message.info("okkk")
                break;
            // repairingRoomOption
            case '9':
                //  清洁完成
                roomRequest.finishedCleanStatus({
                    roomId: rowData.roomId,
                }).then(resp => {
                    if (resp.data.code == 200) {
                        message.success("打扫完成")
                        // rowData.roomStatus = "打扫中"
                        //// TODO wrap here
                        getRoomDetailInfoData();
                        getStatistics();
                    } else {
                        message.error(`${resp.data.message}"`)
                    }
                })
                break;
            case '10':
                //  恢复使用
                roomRequest.updateRoomStatus({
                    roomId: rowData.roomId,
                    roomStatus: 0,
                }).then(resp => {
                    if (resp.data.code == 200) {
                        message.success("修改成功")
                        // rowData.roomStatus = "空闲"
                        //// TODO wrap here
                        getRoomDetailInfoData();
                        getStatistics();
                    } else {
                        message.error(`${resp.data.message}"`)
                    }
                })
                break;
        }
    }
});

const usedRoomOption = [
    {
        label: '退房',
        key: '1',
    }, {
        label: '清洁服务',
        key: '2',
    }, {
        label: '查询住户消息',
        key: '3',
    }
]
const vacancyRoomOption = [
    {
        label: '入住',
        key: '4',
    }, {
        label: '打扫',
        key: '5',
    }, {
        label: '暂停出售',
        key: '6',
    }
]

const orderedRoomOption = [
    {
        label: '取消预订',
        key: '7',
    }, {
        label: '查询住户消息',
        key: '8',
    }
]

const repairingRoomOption = [
    {
        label: '清洁完成',
        key: '9',
    }
]

const canceledRoomOption = [
    {
        label: '恢复使用',
        key: '10'
    }
]

const roomGuestUserList = reactive<{
        userId: number,
        userName: string,
        userNickname: string,
        telephone: string,
        userGender: string,
        userAge: number,
        residentId: string,
        checkInTime:string,
        checkOutTime: string
}[]>([])

const checkInUserRules = {
    userNickname: {
       required: true,
       message: '请输入姓名',
       trigger: 'blur'
    },
    userAge: {
        required: true,
        message: '请输入年龄',
        trigger: ['input', 'blur']
    },
    telephone: {
        required: true,
        message: '请输入电话号码',
        trigger: ['input']
    },
    residentId: {
        required: true,
        message: '请输入身份证号',
        trigger: ['input']
    },
    userGender: {
        required: true,
        message: '请输入性别',
        trigger: ['input']
    }
}

const range = ref<[number, number]>();

const formValue = ref<{
    userNickname: string,
    userAge: string,
    userGender: string,
    telephone: string,
    residentId: string,
}>({
    userNickname:'',
    userAge: '',
    userGender: '',
    telephone: '',
    residentId: '',
})
const currentRoomId = ref<number>();
const confirmCheckIn = () => {
    checkInUserInfo.value.estimatedCheckInTime = range.value?.[0] ?? 0
    checkInUserInfo.value.estimatedCheckOutTime = range.value?.[1] ?? 0
    checkInUserInfo.value.roomId = currentRoomId.value ??0
    sendCheckInRequest(checkInUserInfo.value)
}

const sendCheckInRequest = (checkInUserInfo: any) => {
    roomRequest.checkInUser(checkInUserInfo).then(resp => {
        if (resp.data.code == 200) {
            message.success("入住成功")
            getRoomDetailInfoData();
            getStatistics();
        } else {
            message.error("入住失败")
        }
    })
}

const handleUserAddClick = () => {
    checkInUserInfo.value?.userInfoList.push(formValue.value)
    message.success("添加成功")
}

const checkInUserInfo = ref<{
    userInfoList: {
            userNickname: string,
            userAge: string,
            userGender: string,
            telephone: string,
            residentId: string,
        }[], 
    estimatedCheckInTime: number,
    estimatedCheckOutTime: number,
    roomId: number
}>({
    userInfoList: [],
    estimatedCheckInTime: 0,
    estimatedCheckOutTime: 0,
    roomId: 0,
})

onMounted(async () => {
    getStatistics()
    getRoomDetailInfoData();
})
</script>

<style lang="less" scoped>
.room-manage-wrap {
    height: 97%;
    width: 100%;
    overflow: auto;

    .page-header {
        margin: 10px;
        margin-left: 20px;
        border-radius: 10px;
    }

    .room-board {
        height: 100%;
        margin: 10px;
        margin-left: 20px;
        border-radius: 10px;
    }
}
</style>